<template>
  <div class="clearfix">
    <a-upload
      :customRequest="customUpload"
      :remove='remove'
      listType="picture-card"
      :fileList="fileList"
      :multiple="true"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < 9">
        <a-icon type="plus" />
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" :src="imgShowUrl + previewImage" />
    </a-modal>
  </div>
</template>

<script>
// import { getToken } from 'api/qiniu'
import { imgUpload } from '@/views/sys/modules/upload/upload'
import baseapi from '@/api/base'

function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = error => reject(error)
  })
}

export default {
  name: 'ImgUpload',
  props: {
    color: {
      type: String,
      default: '#1890ff'
    },
    uploadUrl: {
      default: baseapi.imgUploadUrl,
      required: false,
      type: String
    },
    appId: {
      default: baseapi.huiwcore_app,
      required: false,
      type: String
    },
    idno: {
      default: 'idno',
      required: false,
      type: String
    },
    imgShowUrl: {
      default: baseapi.imgShowUrl,
      required: false,
      type: String
    },
    placeholder: {
      default: '',
      required: false,
      type: String
    }
  },
  data () {
    return {
      previewVisible: false,
      visible: false,
      previewImage: '',
      listObj: {},
      fileList: [],
      filePathUrl: [],
      uploadHeaders: {
        'appId': this.appId,
        'idno': this.idno
      },
      uploadData: {}
    }
  },
  methods: {
    openModal () {
      this.visible = true
    },
    //点击移除时删除filePathUrl的url
    remove(option){
      console.log(option);
      this.filePathUrl=this.filePathUrl.filter(item=>{return item!=option.url})
      this.$emit('change', this.filePathUrl.join(','))
    },
    customUpload (option) {
      const _this = this
      const formData = new FormData()
      formData.append('appId', _this.appId)
      formData.append('idno', _this.idno)
      formData.append('fileTitle', option.file.name)
      formData.append('file', option.file)
      new Promise((resolve) => {
        _this.loading = 'loading'
        resolve(imgUpload(formData, {}))
      }).then((res) => {
        let index=this.fileList.findIndex(item=>{return item.uid==option.file.uid})
        console.log(index);
        if (res && res.code && res.code === 'C1' && res.data) {
          console.log('上传成功');
          this.fileList[index].status='done'
          this.fileList[index].url = res.data.mobileUrl
          this.filePathUrl.push(res.data.mobileUrl)
          this.$emit('change', this.filePathUrl.join(','))
        }else{
          this.$message.error({content:'上传出错，请检查图片格式'})
          this.fileList[index].status='error'
        }
        
      }).catch(() => {
        this.$message.error({content:'上传出错，请检查图片格式'})
        let index=this.fileList.findIndex(item=>{return item.uid==option.file.uid})
        this.fileList[index].status='error'
      }).finally(() => {
        // do
      })
    },
    handleCancel () {
      this.previewVisible = false
    },
    async handlePreview (file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      } else {
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange ({ fileList }) {
      this.fileList = fileList
    },
    uploadModalHandleOk () {
      this.$emit('successCBK', this.filePathUrl)
      this.fileList = []
      this.visible = false
    },
    uploadModalHandleCancel () {
      this.uploadModalHandleClose()
    },
    uploadModalHandleClose () {
      this.visible = false
    }
  }
}
</script>

<style lang="less" scoped>
/* you can make up upload button and sample style by using stylesheets */
  .clearfix {
    min-height: 140px !important;
    margin: 5px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }
</style>
